#include "AuthenticationList.h"
#include "ui_AuthenticationList.h"
#include "Models/DeviceAuthentication.h"
#include "Component/AuthenticationCard.h"
#include "Tools/MyUrl.h"
#include "Tools/UiUpdateMediator.h"

#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QPushButton>

AuthenticationList::AuthenticationList(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AuthenticationList)
{
    ui->setupUi(this);
    connect(UiUpdateMediator::getInstance(), &UiUpdateMediator::updateAuthentication,this, &AuthenticationList::InitUi);
    this->layout = nullptr;
    this->InitUi();
}

void AuthenticationList::InitUi()
{
    if(this->layout)
    {
        delete this->layout;
    }
    this->layout = new QVBoxLayout(this->ui->widget_cards);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply){
        QJsonParseError parseError;
        QJsonDocument jsonData = QJsonDocument::fromJson(reply->readAll(), &parseError);

        qDebug() << jsonData;

        if (parseError.error != QJsonParseError::NoError)
        {
            qDebug() << "JSON 解析失败：" << parseError.errorString() << __LINE__ << __FILE_NAME__;
            return;
        }

        QJsonArray deviceArray = jsonData.array();

        for(const QJsonValue &value: deviceArray)
        {

            QJsonObject deviceJson = value.toObject();

            DeviceAuthentication* device_info = new DeviceAuthentication(
                deviceJson["device_id"].toString(),
                deviceJson["username"].toString(),
                deviceJson["password"].toString()
            );

            AuthenticationCard* card = new AuthenticationCard(device_info);
            connect(card, &AuthenticationCard::updateUi, this, &AuthenticationList::InitUi);
            this->layout->addWidget(card);

        }
    });

    QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::authSelect));
    request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    manager->get(*request);
}

AuthenticationList::~AuthenticationList()
{
    delete ui;
}
